package com.taptech.doufu.services.personalcenter;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.Toast;

import com.taptech.doufu.util.FileUtil;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.listener.ILoginCallback;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.util.NotifyUtil;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.connect.share.QQShare;
import com.tencent.open.SocialConstants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

public class QQService {

	private static QQService instance = new QQService();


	private static Tencent mTencent;
	private static QQAuth mQQAuth;
	private UserInfo mInfo;
	private boolean isLogin;

	private QQService() {
		init();
		SharedPreferences pres = QQTokenKeeper
				.readAccessToken(WeMediaApplication.applicationContext);
		if (pres != null) {
			String token = pres.getString(QQTokenKeeper.ACCESS_TOKEN, null);
			String openId = pres.getString(QQTokenKeeper.OPENID, null);
			if (token != null && openId != null) {
				initToken(token, openId);
			}
		}
	}

	public static QQService getInstance() {
		return instance;
	}

	public void initToken(String token, String openId) {
		mTencent.setAccessToken(token, System.currentTimeMillis() + "");
		mTencent.setOpenId(openId);
		mQQAuth.setAccessToken(token, System.currentTimeMillis() + "");
		mQQAuth.setOpenId(WeMediaApplication.applicationContext, openId);
	}

	private void init() {
		if (mTencent == null || !mTencent.isSessionValid()) {
			mTencent = Tencent.createInstance(Constant.APP_ID,
					WeMediaApplication.applicationContext);
		}
		if (mQQAuth == null || !mQQAuth.isSessionValid()) {
			mQQAuth = QQAuth.createInstance(Constant.APP_ID,
					WeMediaApplication.applicationContext);
		}
	}

	public void login(final Activity activity, final ILoginCallback callback) {
		if (isLogin == true) {
			UIUtil.toastMessage(activity, "别点了，QQ正在启动...");
			return;
		}
		isLogin = true;
		if (mTencent.isSessionValid()) {
			mTencent.logout(activity);
		}
		mTencent.login(activity, Constant.SCOPE, new IUiListener() {
			@Override
			public void onComplete(Object response) {
				TTLog.s("response===" + response.toString());
				doComplete((JSONObject) response);
				QQTokenKeeper.writeAccessToken(
						WeMediaApplication.applicationContext,
						(JSONObject) response);
				isLogin = false;
			}

			protected void doComplete(JSONObject values) {
				UIUtil.toastMessage(activity, "QQ授权成功，正在获取用户信息");
				getUserInfo(activity, values,callback);
			}

			@Override
			public void onError(UiError e) {
				callback.token("","","QQ登录异常:" + e.errorMessage);
				UIUtil.toastMessage(activity, "QQ登录异常:" + e.errorMessage);
				UIUtil.dismissDialog();
				isLogin = false;
			}

			@Override
			public void onCancel() {
				callback.token("","","授权失败，请重新登录");
				UIUtil.dismissDialog();
				isLogin = false;
			}
		});

	}



	private void getUserInfo(final Activity activity, final JSONObject infos, final ILoginCallback callback) {
		if (mQQAuth != null && mQQAuth.isSessionValid()) {
			IUiListener listener = new IUiListener() {
				@Override
				public void onError(UiError e) {
					UIUtil.dismissDialog();
				}

				@Override
				public void onComplete(final Object response) {
					UIUtil.dismissDialog();
					String openId = DiaobaoUtil.getStringFromJSONObject(
							infos, "openid");
					String token = DiaobaoUtil.getStringFromJSONObject(infos,
							"access_token");
					callback.token(token,openId,"");
				}

				@Override
				public void onCancel() {
					UIUtil.dismissDialog();
				}
			};
			UIUtil.showProgressDialog(activity);
			mInfo = new UserInfo(activity, mQQAuth.getQQToken());
			mInfo.getUserInfo(listener);
		}
	}



	/**
	 * 分享到qq
	 * @param activity
	 * @param shareInfo
	 */
	public void shareToQQ(final Activity activity, final ShareBeansInfo shareInfo){
		if (shareInfo == null) {
			return;
		}
		final Bundle params = new Bundle();
		params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "豆花");
		if (shareInfo.getDataType() == Constant.ShareDataType.SHARE_DATA_TYPE_IMAGE) { //分享图片
			params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
					QQShare.SHARE_TO_QQ_TYPE_IMAGE);
			if (shareInfo.getImagUrl().startsWith("http")) {
				//检查文件是否存在
				//// TODO: 16/11/16 优化根据 md5 值 判断文件
				BaseSubscriber<File> baseSubscriber = new BaseSubscriber<File>() {
					@Override
					public void onError(Throwable e) {
						e.printStackTrace();
						Toast.makeText(activity, "分享失败", Toast.LENGTH_LONG).show();
					}

					@Override
					public void onNext(File file) {
						params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,file.getPath());
						shareToQQ(activity, shareInfo, params);
					}
				};
				RxJavaHelper.downloadFile(shareInfo.getImagUrl(),baseSubscriber, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsoluteFile(), System.currentTimeMillis()+".jpg" );
			}else{
				params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,shareInfo.getImagUrl());
				shareToQQ(activity, shareInfo, params);
			}

		}else{
			params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
					QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
			params.putString(QQShare.SHARE_TO_QQ_TITLE, shareInfo.getTitle());
			params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareInfo.getShartText());
			params.putString(QQShare.SHARE_TO_QQ_EXT_STR, shareInfo.getShartText());
			params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareInfo.getShareUrl());
			if (!TextUtils.isEmpty(shareInfo.getImagUrl())) {
				params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, shareInfo.getImagUrl());
			}else{
				params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, Constant.SHARE_IMAG_URL);
			}
			shareToQQ(activity, shareInfo, params);
		}


	}

	private void shareToQQ(final Activity activity, final ShareBeansInfo shareInfo, Bundle params) {
		QQService.getInstance().shareToQQ(activity, params, new IUiListener() {

			@Override
			public void onError(UiError arg0) {
				if(shareInfo != null &&shareInfo.isForWeex()){
					NotifyUtil.shareNotify("分享失败");
				}
			}

			@Override
			public void onComplete(Object arg0) {
				if(shareInfo != null &&shareInfo.isForWeex()){
					NotifyUtil.shareNotify("分享成功");
				}
				if (shareInfo.getId() != null ) {
					HomeMainServices.shareStatistics(activity,
							String.valueOf(shareInfo.getSocial_type()),
							shareInfo.getObject_type(),shareInfo.getId(),shareInfo.shareUrl);
				}

			}

			@Override
			public void onCancel() {
				if(shareInfo != null &&shareInfo.isForWeex()){
					NotifyUtil.shareNotify("分享取消");
				}
				TTLog.d("tag", "task has been canceled");
			}
		});
	}


	/**
	 * 分享到qq空间
	 * @param activity
	 * @param shareInfo
	 */
	public void shareQQSpace(final Activity activity, final ShareBeansInfo shareInfo) {
		if (shareInfo == null) {
			return;
		}
		final Bundle params = new Bundle();
		if (shareInfo.getDataType() == Constant.ShareDataType.SHARE_DATA_TYPE_IMAGE) { //分享图片
			params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
					QQShare.SHARE_TO_QQ_TYPE_IMAGE);
			params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
			if (shareInfo.getImagUrl().startsWith("http")) {
				//检查文件是否存在
				//// TODO: 16/11/16 优化根据 md5 值 判断文件
				BaseSubscriber<File> baseSubscriber = new BaseSubscriber<File>() {
					@Override
					public void onError(Throwable e) {
						e.printStackTrace();
						Toast.makeText(activity, "分享失败", Toast.LENGTH_LONG).show();
					}

					@Override
					public void onNext(File file) {
						params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, file.getPath());
						shareToQQ(activity, shareInfo, params);
					}
				};
				RxJavaHelper.downloadFile(shareInfo.getImagUrl(),baseSubscriber, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsoluteFile(), System.currentTimeMillis()+".jpg" );
			}else{
				params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, shareInfo.getImagUrl());
				shareToQQ(activity, shareInfo, params);
			}

		}else{
			params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
					QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
			params.putString(QQShare.SHARE_TO_QQ_TITLE, shareInfo.getTitle());// 必填
			params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareInfo.getShartText());// 选填
			params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareInfo.getShareUrl());// 必填
			ArrayList<String> imgs = new ArrayList<>();
			if (!TextUtils.isEmpty(shareInfo.getImagUrl())) {
				imgs.add(shareInfo.getImagUrl());
			}else{
				imgs.add(Constant.SHARE_IMAG_URL);
			}
			params.putStringArrayList(QQShare.SHARE_TO_QQ_IMAGE_URL, imgs);
			shareToQzone(activity, shareInfo, params);
		}

	}

	private void shareToQzone(final Activity activity, final ShareBeansInfo shareInfo, Bundle params) {
		QQService.getInstance().shareToQZone(activity, params,
				new IUiListener() {

					@Override
					public void onError(UiError arg0) {
						if (shareInfo != null && shareInfo.isForWeex()) {
							NotifyUtil.shareNotify("分享失败");
						}
						TTLog.s(arg0.errorCode + ":::::" + arg0.errorMessage);
					}

					@Override
					public void onComplete(Object arg0) {
						if (shareInfo != null &&shareInfo.isForWeex()) {
							NotifyUtil.shareNotify("分享成功");
						}else{
							if (shareInfo!=null && shareInfo.getId() != null) {
								HomeMainServices.shareStatistics(activity,
										String.valueOf(shareInfo.getSocial_type()),
										shareInfo.getObject_type(),shareInfo.getId(),shareInfo.shareUrl);
							}
						}
					}

					@Override
					public void onCancel() {
						if (shareInfo != null &&shareInfo.isForWeex()) {
							NotifyUtil.shareNotify("分享取消");
						}
					}
				});
	}

	public void shareToQQ(Activity activity, Bundle params, IUiListener listener) {

		mTencent.shareToQQ(activity, params, listener);
		// mTencent.
	}

	public void shareToQZone(Activity activity, Bundle params,
			IUiListener listener) {
		mTencent.shareToQzone(activity, params, listener);
	}

	public void shareApp(Activity activity, Bundle params, IUiListener listener) {
		if (mTencent.isSessionValid() && mTencent.getOpenId() != null) {
			mTencent.story(activity, params, listener);
		}

		// BaseApi api = new BaseApi() {
		// };ba
	}

	public void invite(final Activity activity) {
		if (mTencent.isReady()) {
			Bundle params = new Bundle();
			params.putString(SocialConstants.PARAM_APP_ICON,
					"http://imgcache.qq.com/qzone/space_item/pre/0/66768.gif");
			params.putString(SocialConstants.PARAM_APP_DESC, "超级豆花，进来看看报");
			params.putString(SocialConstants.PARAM_ACT, "进入应用");
			mTencent.invite(activity, params, new IUiListener() {
				@Override
				public void onError(UiError arg0) {
				}

				@Override
				public void onComplete(Object arg0) {
					UIUtil.toastMessage(activity, "邀请好友成功");
				}

				@Override
				public void onCancel() {

				}
			});

		}
	}

}
